package csd.wyaiyr.com.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.github.pagehelper.PageHelper;
import csd.wyaiyr.com.config.*;
import csd.wyaiyr.com.mapper.AiAdviceMapper;
import csd.wyaiyr.com.mapper.MonitorDataMapper;
import csd.wyaiyr.com.model.AiAdvice;
import csd.wyaiyr.com.model.MonitorData;
import csd.wyaiyr.com.model.dto.MoniDataQueryPageReqDto;
import csd.wyaiyr.com.service.SolimonitorService;

import csd.wyaiyr.com.utils.DateUtil;
import csd.wyaiyr.com.utils.StringUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class SolimonitorServiceImpl extends BaseServiceImpl<MonitorData> implements SolimonitorService {

    @Value("${monitor.mintemp}")
    private BigDecimal minTemp;

    @Value("${monitor.maxtemp}")
    private BigDecimal maxtemp;

    @Value("${monitor.minhumi}")
    private BigDecimal minhumi;

    @Value("${monitor.maxhumi}")
    private BigDecimal maxhumi;


    @Value("${aliyun.qianwen.qwApikey}")
    private String qwApikey;
    @Value("${aliyun.qianwen.qwModel}")
    private String qwModel;


    @Autowired
    private MonitorDataMapper monitorDataMapper;

    @Autowired
    private AiAdviceMapper aiAdviceMapper;

    @Override
    public BaseResult insert(MonitorData monitorData) {
        if(null == monitorData.getHumi() || null == monitorData.getTemp()){
            log.error("温度或湿度为空");
            return null;
        }else{
            monitorData.setId(UUID.randomUUID().toString().replaceAll("-",""));
            monitorData.setReportTime(new Date());
            monitorData.setWornFlag("0");

            if(monitorData.getTemp().compareTo(minTemp) < 0 || monitorData.getTemp().compareTo(maxtemp) > 0){
                monitorData.setWornFlag("1");
                monitorData.setWornInfo("温度异常");
            }

            if(monitorData.getHumi().compareTo(minhumi) < 0 || monitorData.getHumi().compareTo(maxhumi) > 0){
                monitorData.setWornFlag("1");
                if(!StringUtil.isEmpty(monitorData.getWornInfo())){
                    monitorData.setWornInfo(monitorData.getWornInfo()+","+"湿度异常");
                }else{
                    monitorData.setWornInfo("湿度异常");
                }
            }
        }

        int insert = monitorDataMapper.insert(monitorData);
        if(insert > 0){
            return BaseResult.ok("成功");
        }else{
            return BaseResult.error("失败");
        }
    }


    @Override
    public BaseResultPage list(MoniDataQueryPageReqDto pageReqDto) {
        QueryPage page = pageReqDto.getQueryPage();
        Result<List<MonitorData>> result = new Result<>();
        Boolean needPage = false;
        if (null != page && "true".equals(page.getIsNeedPage())) {
            needPage = true;
        }
        if (needPage) {
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
        }

        if("2".equals(pageReqDto.getWornFlag())){
            pageReqDto.setWornFlag(null);
        }

        //告警标识
        List<MonitorData> userList = monitorDataMapper.getList(pageReqDto);

        if (needPage) {
            result.setPage(getPage(userList, page));
        }
        result.setSuccess(true);
        result.setData(userList);
        return BaseResultPage.ok(result.getData(),result.getPage());
    }


    @Override
    public BaseResultPage advicelist(MoniDataQueryPageReqDto pageReqDto) {
        QueryPage page = pageReqDto.getQueryPage();
        Result<List<AiAdvice>> result = new Result<>();
        Boolean needPage = false;
        if (null != page && "true".equals(page.getIsNeedPage())) {
            needPage = true;
        }
        if (needPage) {
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
        }

        if("2".equals(pageReqDto.getWornFlag())){
            pageReqDto.setWornFlag(null);
        }

        //告警标识
        List<AiAdvice> userList = aiAdviceMapper.getListByDate(pageReqDto.getReportTime());

        if (needPage) {
            result.setPage(getPage(userList, page));
        }
        result.setSuccess(true);
        result.setData(userList);
        return BaseResultPage.ok(result.getData(),result.getPage());
    }

    @Override
    public BaseResult getAiAdviceBydate(String datestr) {

        MonitorData monitorData = monitorDataMapper.getavgdataBydate(datestr);
        if(null != monitorData){
            //调用ai接口
            log.info("调用ai接口");
            String avgdata = "温度："+monitorData.getTemp()+"，湿度："+monitorData.getHumi() + "%";
            String aiAdviceResult = execAifx(avgdata);
            //保存至数据库
            AiAdvice aiAdvice = new AiAdvice();
            aiAdvice.setId(UUID.randomUUID().toString().replaceAll("-",""));
            aiAdvice.setAiParam(avgdata);
            aiAdvice.setAiAdvice(aiAdviceResult);
            aiAdvice.setAdviceTime(new Date());
            aiAdviceMapper.insert(aiAdvice);
            return BaseResult.ok("成功");
        }else{
            return BaseResult.error("无数据");
        }

    }


    @SneakyThrows
    public String execAifx(String avgdata) {

        //查询对话记录拼接分析内容
        String rgfx_rule = "当前土壤监测平均数据值如下：["+avgdata+"],请从农作物生长角度出发，分析可能带来的影响，以及应对措施，结果按照：影响是什么什么、应对措施是xxx 输出。 要求输出结果中不要带有AI分析语言的词语，言简意赅，且以JSON" +
                "数据格式输出。" ;

        Generation gen = new Generation();

        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("你是一名经验丰富农业科学家")
                .build();

        log.info("调用千问模型提问：{}",rgfx_rule);

        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                //提问
                .content(rgfx_rule)
                .build();


        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用阿里云百炼API Key将下行替换为：.apiKey("sk-xxx")
                //.apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .apiKey(qwApikey)
                // 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                .model(qwModel)
                .enableSearch(false)
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();

        //获取总结
        GenerationResult result = gen.call(param);
        String content = result.getOutput().getChoices().get(0).getMessage().getContent();
//        JSONObject  jsonObject = JSONObject.parseObject(content);
        log.info("ai分析结果：{}",content);
        return content;
    }
}
